package cz.data.domain.oss.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cz.data.common.base.BaseController;
import cz.data.common.base.BaseResponse;
import cz.data.common.base.SimpleDataResponse;
import cz.data.common.base.TableDataResponse;
import cz.data.domain.oss.mapstruct.FileMapper;
import cz.data.domain.oss.model.entity.FileEntity;
import cz.data.domain.oss.model.query.FileQuery;
import cz.data.domain.oss.model.vo.FileVo;
import cz.data.domain.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = {"文件管理"})
@RestController
@RequestMapping("/files")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileMapper fileMapper;

    @ApiOperation(value = "文件管理-详情")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @GetMapping("/{id}")
    public SimpleDataResponse<FileEntity> getFileById(@PathVariable String id) {
        return new SimpleDataResponse<>(fileService.getById(id));
    }

    @ApiOperation(value = "文件管理-分页查询")
    @ApiImplicitParam(name = "fileQuery", value = "查询实体fileQuery", required = true, dataTypeClass = FileQuery.class)
    @GetMapping("/page")
    public TableDataResponse<FileVo> getFilePage(FileQuery fileQuery) {
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        IPage<FileEntity> page = fileService.page(new Page<>(fileQuery.getPageNum(), fileQuery.getPageSize()), queryWrapper);
        List<FileVo> collect = page.getRecords().stream().map(fileMapper::toVO).collect(Collectors.toList());
        return new TableDataResponse<>(collect, page.getTotal());
    }

    @ApiOperation(value = "文件管理-附件上传")
    @ApiImplicitParam(name = "cz/data/domain/oss", value = "附件file", required = true, dataTypeClass = MultipartFile.class)
    @PostMapping("/upload")
    public BaseResponse upload(@RequestParam("cz/data/domain/oss") MultipartFile file) {
        fileService.uploadFile(file);
        return BaseResponse.success();
    }

    @ApiOperation(value = "文件管理-删除")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @DeleteMapping("/{id}")
    public BaseResponse deleteFileById(@PathVariable String id) {
        fileService.deleteFileById(id);
        return BaseResponse.success();
    }
}

